<template>
  <div class="add">
    <div class="add_header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card shadow="hover" class="add_con">
      <el-alert title="添加商品信息" type="info" show-icon center :closable='false'>
      </el-alert>
      <!-- 横向步骤条 -->
      <el-steps :active="activeX - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <div class="">
        <!-- 竖向步骤条 -->
        <el-tabs tab-position="left" v-model="activeX" @tab-click="handBasicClick"
          :before-leave="beforeLeave">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form ref="basicForm" :rules="basicRules" :model="basicInfo">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="basicInfo.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model.number="basicInfo.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model.number="basicInfo.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model.number="basicInfo.goods_number"></el-input>
              </el-form-item>
              <!-- 三级联表 -->
              <el-form-item prop="goods_cat" label="商品分类">
                <el-cascader v-model="basicInfo.goods_cat" :options="catelist"
                  @change="handleThreeChange" :props="cateProps" clearable></el-cascader>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <div class="" v-for="item in parameter" :key="item.attr_id">
              <span>{{item.attr_name}}</span>
              <el-checkbox-group v-model="item.attr_vals" style="margin: 20px 0;">
                <el-checkbox :label="items" border v-for="(items,index) in item.attr_vals"
                  :key="index"></el-checkbox>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <div class="" v-for="item in attribute" :key="item.attr_id" style="margin: 20px 0;">
              <span style="margin-bottom: 10px;">{{item.attr_name}}</span>
              <el-input v-model="item.attr_vals"></el-input>
            </div>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList"
              list-type="picture" :headers="gettoken" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="basicInfo.goods_introduce" />
            <el-button class="Add" type="primary" @click="goodsAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="dialogBigImgVisible">
        <img :src="dialogImgurl" alt="" srcset="">
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogBigImgVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'aDd',
  data() {
    return {
      // 横向步骤条步骤
      activeX: '0',
      // 添加商品结果
      basicInfo: {
        goods_name: '',
        goods_cat: [],
        goods_price: ''.number,
        goods_number: ''.number,
        goods_weight: ''.number,
        goods_introduce: '',
        pics: [],
        attrs: [],
      },
      // 基本信息校验
      basicRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
      },
      // 基本信息三级链表数据
      catelist: [],
      // 三级联表格式
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      // 商品参数可选数据
      parameter: [],
      // 商品属性可选数据
      attribute: [],
      // 上传图片的文件列表
      fileList: [],
      //  上传图片组件需要手动添加token请求头
      gettoken: { Authorization: window.sessionStorage.token },
      // 图片预览框的显示
      dialogBigImgVisible: false,
      // 图片预览时选中的图片路径
      dialogImgurl: '',
    }
  },
  methods: {
    // 基本页获取三级链表数据
    async getCatelist() {
      const { data: getcateListres } = await this.$http.get('categories')
      // console.log(getcateListres)
      this.catelist = getcateListres.data
    },
    // 切换竖向步骤标签之前的钩子
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.basicInfo.goods_cat.length === 0) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 基本信息页竖向步骤更改后
    handBasicClick() {
      if (this.activeX === '0') {
        this.getCatelist()
      }
      if (this.activeX === '1') {
        const manyOnly = 'many'
        this.manyOnlyinfo(manyOnly)
      }
      if (this.activeX === '2') {
        const manyOnly = 'only'
        this.manyOnlyinfo(manyOnly)
      }
    },
    // 获取动、静态数据
    async manyOnlyinfo(manyOnly) {
      const attrID = this.basicInfo.goods_cat[2]
      const { data: handleChangeres } = await this.$http.get(`categories/${attrID}/attributes`, {
        params: { sel: manyOnly },
      })
      if (handleChangeres.meta.status != 200) {
        this.$message.error('抱歉，获取失败')
        return
      }
      console.log(handleChangeres)

      if (manyOnly === 'many') {
        handleChangeres.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.parameter = handleChangeres.data
      } else if (manyOnly === 'only') {
        this.attribute = handleChangeres.data
      }
      this.$message.success('获取成功')
    },
    // 基本信息页三级链表选择后
    handleThreeChange() {
      if (this.basicInfo.goods_cat.length != 3) {
        this.basicInfo.goods_cat = []
        this.$message.error('请选择三级列表')
        return
      }
    },
    // 文件列表移除文件时
    handleRemove(file) {
      const picinfo = file.response.data.tmp_path
      const index = this.basicInfo.pics.findIndex((x) => {
        x.pic === picinfo
      })
      this.basicInfo.pics.splice(index, 1)
    },
    // 点击文件列表中已上传的文件时
    handlePreview(file) {
      this.dialogBigImgVisible = true
      this.dialogImgurl = file.url
    },
    // 文件上传成功时
    handleSuccess(response) {
      const pic = { pic: response.data.tmp_path }
      this.basicInfo.pics.push(pic)
    },
    // 关闭添加框前提示
    handleClose(done) {
      this.$confirm('确认关闭?填写数据将不被保存')
        .then(() => {
          done()
        })
        .catch(() => {})
    },
    // 添加商品
    goodsAdd() {
      this.$refs.basicForm.validate(async (val) => {
        if (!val) {
          this.$message.error('请检查必填商品信息')
          return
        }
        // 按要求完成商品参数数组
        this.parameter.forEach((item) => {
          this.basicInfo.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(),
          })
        })
        this.attribute.forEach((item) => {
          this.basicInfo.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          })
        })
        // 按要求完成三级链表字符串
        this.basicInfo.goods_cat = this.basicInfo.goods_cat.join()
        // console.log(this.basicInfo)
        const { data: addres } = await this.$http.post('goods', this.basicInfo)
        console.log(addres)
        if (addres.meta.status != 201 && addres.meta.status != 1) {
          this.$message.error('添加失败')
          this.$router.push('/goods')
          return
        }
        this.$message.success('添加成功')
        this.$router.push('/goods')
      })
    },
  },
  created() {
    this.getCatelist()
  },
}
</script>

<style lang='less' scoped>
.add_header {
  .el-breadcrumb {
    font-size: 17px;
  }
}
.add_con {
  margin-top: 30px;
  height: 90%;
  background: #fff;
  padding: 20px;
  .el-steps {
    margin: 20px 0;
  }
}
.el-tab-pane {
  .el-input {
    margin-top: 15px;
  }
}
.el-dialog {
  img {
    width: 100%;
  }
}
.Add {
  margin-top: 20px;
}
</style>